/* eslint-disable */
import { computed, nextTick, ref } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { singleUpload, splitUpload } from '@/utils/upload'
import { getImageSize } from '@/utils/tools'
import { uploadByUrl } from '@/api/file'
import axios from 'axios'

import tinymce from 'tinymce/tinymce' //tinymce默认hidden，不引入则不显示编辑器
import 'tinymce/themes/silver' //编辑器主题，不引入则报错
import 'tinymce/icons/default' //引入编辑器图标icon，不引入则不显示对应图标
// 引入编辑器插件(几乎免费全部内容)
import 'tinymce/plugins/advlist' //高级列表
import 'tinymce/plugins/anchor' //锚点
import 'tinymce/plugins/autolink' //自动链接
import 'tinymce/plugins/autoresize' //编辑器高度自适应,注：plugins里引入此插件时，Init里设置的height将失效
import 'tinymce/plugins/autosave' //自动存稿
import 'tinymce/plugins/charmap' //特殊字符
import '/public/tinymce/plugins/code' //编辑源码
import 'tinymce/plugins/codesample' //代码示例
import 'tinymce/plugins/directionality' //文字方向
import 'tinymce/plugins/fullscreen' //全屏
import 'tinymce/plugins/hr' //水平分割线
import 'tinymce/plugins/importcss' //引入css
import 'tinymce/plugins/insertdatetime' //插入日期时间
import '/public/tinymce/plugins/link' //超链接
import 'tinymce/plugins/lists' //列表插件
import 'tinymce/plugins/pagebreak' //插入分页符
import 'tinymce/plugins/paste' //粘贴插件
import 'tinymce/plugins/save' //保存
import 'tinymce/plugins/searchreplace' //查找替换
import 'tinymce/plugins/table' //表格
import 'tinymce/plugins/textcolor' //文字颜色
import '@npkg/tinymce-plugins/indent2em'
import '/public/tinymce/plugins/layout' //一键布局
import '/public/tinymce/plugins/formatpainter/plugin.js' //格式刷

/**
 * 创建tinymce编辑器配置
 * @param {Object} options 配置选项
 * @returns {Object} tinymce配置对象
 */
export function createTinyConfig({ editor135, pasteLoading, handlers, showImgOption, currentImg, curHoverImg, showAxupImgs, showVideoUpload, showFilesUpload, isPasting }) {
  const store = useStore()
  // 从store获取配置
  const clip_port = ref(store.state.content.clip_port)
  const pluginConfig = computed(() => store.state.content.pluginConfig)
  const singleActionUrl = computed(() => store.state.content.singleActionUrl)
  const splitActionUrl = computed(() => store.state.content.splitActionUrl)
  const maxWidth = computed(() => {
    // 允许上传的图片最大宽度
    let currentSite = store.state.site.currentSite
    return currentSite.setting.maxWidth ? currentSite.setting.maxWidth : 2000
  })
  const { handleImgEditor, setAvatarBase64, onContentFrom135 } = handlers

  return {
    language_url: process.env.BASE_URL + 'tinymce/langs/zh_CN.js',
    language: 'zh_CN',
    toolbar_sticky: true,
    skin_url: process.env.BASE_URL + 'tinymce/skins/ui/oxide',
    inline: true,
    plugins: 'searchreplace autolink directionality fullscreen link code codesample table charmap hr anchor insertdatetime advlist lists pagebreak autosave indent2em layout formatpainter',
    toolbar: [
      'code | fullscreen undo redo',
      'formatselect fontselect fontsizeselect | bold italic underline strikethrough forecolor backcolor subscript superscript removeformat layout formatpainter',
      'bullist | numlist',
      'alignleft aligncenter | alignright alignjustify',
      'outdent indent | indent2em lineheight',
      'charmap hr | insertdatetime',
      'table tabledelete tableinsertrowbefore tableinsertrowafter | tabledeleterow tableinsertcolbefore tableinsertcolafter tabledeletecol',
      'selectall | searchreplace',
      '135Editor | xiumi',
      'imgsedit axupimgs axupvideo axupfiles onlineImgEdit'
    ],
    layout_options: {
      style: {
        'text-indent': '2em',
        'line-height': '2',
        'font-family': '微软雅黑',
        'font-size': '16px'
      },
      filterTags: ['table>*', 'tbody>*'],
      clearStyle: ['position', 'top', 'bottom'],
      tagsStyle: {
        'p,p>span,span': {
          'text-indent': '2em',
          'line-height': '2',
          'font-family': '微软雅黑',
          'font-size': '16px'
        },
        font: { 'font-family': '微软雅黑' },
        img: { display: 'block', 'margin-left': 'auto', 'margin-right': 'auto', height: 'auto' }
      }
    },
    custom_ui_selector: 'body',
    automatic_uploads: true,
    menubar: 'edit insert view format tools table',
    menu: {
      edit: {
        title: '编辑',
        items: 'undo redo | cut copy paste pastetext | selectall'
      },
      insert: { title: '插入', items: 'link axupimgs axupvideo axupfiles onlineImgEdit |  hr' },
      view: { title: '查看', items: 'visualaid' }
    },
    fontsize_formats: '12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px',
    font_formats:
      '微软雅黑=Microsoft YaHei;苹果苹方=PingFang SC;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
    height: 600,
    placeholder: '',
    icons: 'tinyhcs',
    icons_url: process.env.BASE_URL + 'tinymce/icons/tinyhcs/icons.js',
    extended_valid_elements:
      'svg[*],foreignobject[*],defs[*],pattern[*],desc[*],metadata[*],g[*],mask[*],path[*],line[*],marker[*],rect[*],circle[*],ellipse[*],polygon[*],polyline[*],linearGradient[*],radialGradient[*],stop[*],image[*],view[*],text[*],textPath[*],title[*],tspan[*],glyph[*],symbol[*],switch[*],use[*],img[*]',
    branding: false,
    resize: false,
    statusbar: false,
    elementpath: false,
    fixed_toolbar_container: '#tinymce-box .toolbar',
    content_css: process.env.BASE_URL + 'tinymce/tinycontent.css',
    images_upload_url: singleActionUrl.value,
    convert_urls: false,
    contextmenu: 'link copy myPaste',
    relative_urls: false,

    images_upload_handler: async (blobInfo, success, failure, progress) => {
      let option = {
        file: new File([blobInfo.blob()], blobInfo.filename(), { type: 'image/png' })
      }
      let res = {}
      if (option.file.size > 5 * 1024 * 1024) {
        res = await splitUpload(option.file, splitActionUrl.value, () => {}, 5 * 1024 * 1024)
      } else {
        let data = new FormData()
        data.append('file', option.file)
        const { width, height, scale } = await getImageSize(option.file, maxWidth.value)
        data.append('cropWidth', width)
        data.append('cropHeight', height)
        data.append('scaledWidth', width)
        data.append('scaledHeight', height)
        data.append('startX', 0)
        data.append('startY', 0)
        data.append('path', 'content')
        data.append('type', 0)
        if (scale < 1) {
          data.append('canMini', true)
        }
        res = await singleUpload(data, singleActionUrl.value, () => {})
      }
      if (res.data.url) {
        success(res.data.url)
        setTimeout(function () {
          const editor = tinymce.activeEditor
          const img = editor.dom.select('img[src="' + res.data.url + '"]')[0]
          if (img) {
            editor.dom.setAttrib(img, 'origin-src', res.data.oriUrl ? res.data.oriUrl : res.data.url)
          }
        }, 100)
      }
    },

    init_instance_callback: function (editor) {
      editor.execCommand('selectAll')
      editor.selection.getRng().collapse(false)
      editor.focus()
      
      editor.on('paste', evt => {
        const clipboardData = evt.clipboardData
        const isImage = clipboardData.types.length && clipboardData.types.join('').includes('Files')
        if (pasteLoading.value) return
        // 处理粘贴的base64图片
        const items = clipboardData.items
        for (let i = 0; i < items.length; i++) {
          if (items[i].type.indexOf('image') !== -1) {
            const blob = items[i].getAsFile()
            const reader = new FileReader()
            reader.onload = function (e) {
              const base64Data = e.target.result
              // 创建临时图片元素获取尺寸
              const tempImg = new Image()
              tempImg.src = base64Data
              tempImg.onload = async function () {
                // 转换为Blob并插入
                const response = await fetch(base64Data)
                const blob = await response.blob()
                const blobUrl = URL.createObjectURL(blob)
                editor.insertContent(`<img src="${blobUrl}" />`)
                // TinyMCE 会自动检测到新图片并触发 images_upload_handler
              }
            }
            reader.readAsDataURL(blob)
            evt.preventDefault()
            return
          }
        }

        setTimeout(() => {
          const urlImages = tinymce.activeEditor.dom.doc.querySelectorAll('img[src^="http"]')
          const baseUrl = store.state.base.groupSetting.baseUrl || ''
          let content = tinymce.activeEditor.getContent()
        
          // 处理网络图片
          const processImages = async () => {
            for(let item of urlImages) {
              if(!item.src.includes(baseUrl)) {
                try {
                  const res = await uploadByUrl({url: item.src})
                  if (res.data) {
                    content = content.replace(item.src, res.data)
                  }
                } catch (err) {
                  console.error('Failed to upload image:', err)
                }
              }
            }
            // 所有图片处理完成后，更新编辑器内容
            editor.setContent(content)
            editor.fire('change')
          }
        
          processImages()
        }, 200)

        // 当复制内容不止图片时的处理逻辑
        if (!isImage) {
          if (pluginConfig.value.isUse) {
            evt.preventDefault()
            pasteLoading.value = true

            const checkPromise = url => {
              return new Promise((resolve, reject) => {
                axios
                  .get(url)
                  .then(res => {
                    if (res.data.code) resolve(res)
                    else reject()
                  })
                  .catch(() => reject())
              })
            }

            const precheckClipPort = () => {
              const url = 'http://127.0.0.1:' + clip_port.value + '/clip'
              return checkPromise(url)
                .then(res => {
                  pasteLoading.value = false
                  if (res.data.code === 200) {
                    editor.insertContent(res.data.data)
                    const urlImages = tinymce.activeEditor.dom.doc.querySelectorAll('img[src^="http"]')
                    urlImages.forEach(item => {
                      try {
                        setAvatarBase64(item.src).then(base64 => {
                          item.src = base64
                          tinymce.activeEditor.uploadImages()
                        })
                      } catch {
                        console.log(item.src, 565656)
                      }
                    })
                  } else {
                    ElMessage({
                      message: '无法粘贴该内容',
                      type: 'warning'
                    })
                  }
                  pasteLoading.value = false
                })
                .catch(() => {
                  if (clip_port.value < 10089) {
                    clip_port.value++
                    precheckClipPort()
                  } else {
                    ElMessageBox.confirm('无法粘贴该内容，是否启用粘贴插件工具', '启用确认', {
                      confirmButtonText: '启用',
                      cancelButtonText: '暂不启用'
                    })
                      .then(() => {
                        clip_port.value = store.state.content.clip_port
                        const foxClipLink = document.createElement('a')
                        foxClipLink.href = 'foxc://'
                        foxClipLink.target = '_self'
                        foxClipLink.click()
                        isPasting.value = false
                        nextTick(() => {
                          isPasting.value = true
                        })
                        // 判断用户界面失焦
                        let userOnblur = false
                        window.onblur = function () {
                          userOnblur = true
                        }
                        setTimeout(() => {
                          if (!userOnblur) {
                            ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">下载粘贴插件工具，下载文件包内含安装步骤</p></div>', '下载确认', {
                              distinguishCancelAndClose: true,
                              dangerouslyUseHTMLString: true,
                              confirmButtonText: '确认下载',
                              cancelButtonText: '暂不安装（本次发布不使用插件）'
                            })
                              .then(() => {
                                window.open(pluginConfig.value.downloadLink)
                              })
                              .catch(action => {
                                if (action === 'cancel') pluginConfig.value.isUse = false
                              })
                          }
                        }, 300)
                        pasteLoading.value = false
                      })
                      .catch(() => {
                        pluginConfig.value.isUse = false
                        pasteLoading.value = false
                      })
                  }
                })
            }
            precheckClipPort()
          }
        } else {
          const file = clipboardData.files[0]
          if (!file) return
          if (file.size / 1024 / 1024 > 5) {
            ElMessage.error('上传失败，图片大小请控制在 5M 以内')
            return
          }
          const fileName = file.name?.toLowerCase() || ''
          const ext = fileName.split('.').pop()
          if (!['png', 'gif', 'jpeg', 'jpg'].includes(ext)) {
            ElMessage.error('您粘贴的不是图片，请检查！')
            return
          } else {
            tinymce.activeEditor.uploadImages()
          }
        }
      })

      editor.on('change setContent', function () {
        if (tinymce.activeEditor) {
          let tinyCnt = tinymce.activeEditor.getContent()
          let imgList = []
          if (tinyCnt) {
            imgList = tinymce.activeEditor.dom.select('img')
          }
          if (imgList && imgList.length > 0) {
            imgList.forEach(item => {
              item.onmouseenter = function (e) {
                let btnBox = document.getElementById('img-btn-box')
                btnBox.style.top = e.target.offsetTop + 'px'
                btnBox.style.left = e.target.offsetLeft + 'px'
                showImgOption.value = true
                currentImg.value = item
                curHoverImg.value = item
              }
              item.onmouseleave = function () {
                showImgOption.value = false
              }
            })
          }
        }
      })
    },

    setup: editor => {
      editor.ui.registry.addButton('imgsedit', {
        text: `<div class="image-group"><i class="iconfont">&#xe656;</i><p>编辑图片</p></div>`,
        tooltip: '图片批量编辑',
        onAction: () => handleImgEditor()
      })

      editor.ui.registry.addButton('axupimgs', {
        text: `<div class="image-group"><i class="iconfont">&#xe668;</i><p>插入图片</p></div>`,
        tooltip: '插入图片',
        onAction: () => (showAxupImgs.value = true)
      })

      editor.ui.registry.addMenuItem('axupimgs', {
        text: '插入图片',
        icon: 'axupimgs',
        onAction: () => (showAxupImgs.value = true)
      })

      editor.ui.registry.addButton('axupvideo', {
        text: `<div class="image-group"><i class="iconfont">&#xe659;</i><p>插入视频</p></div>`,
        tooltip: '插入视频',
        onAction: () => (showVideoUpload.value = true)
      })

      editor.ui.registry.addMenuItem('axupvideo', {
        text: '插入视频',
        icon: 'axupvideo',
        onAction: () => (showVideoUpload.value = true)
      })

      editor.ui.registry.addButton('axupfiles', {
        text: `<div class="image-group"><i class="iconfont">&#xe6be;</i><p>插入附件</p></div>`,
        tooltip: '插入附件',
        onAction: () => (showFilesUpload.value = true)
      })

      editor.ui.registry.addMenuItem('axupfiles', {
        text: '插入附件',
        icon: 'axupfiles',
        onAction: () => (showFilesUpload.value = true)
      })

      editor.ui.registry.addButton('135Editor', {
        icon: '135editor',
        tooltip: '135编辑器',
        onAction: () => {
          editor135.value = window.open(
            'https://www.135editor.com/beautify_editor.html?callback=true&appkey=',
            '135editor',
            'height=' + (window.screen.availHeight - 100) + ',width=' + (window.screen.availWidth - 100) + ',top=50,left=50,help=no,resizable=no,status=no,scroll=no'
          )
          window.removeEventListener('message', onContentFrom135)
          window.addEventListener('message', onContentFrom135, false)
        }
      })

      editor.ui.registry.addButton('xiumi', {
        icon: 'xiumi',
        tooltip: 'xiumi编辑器',
        onAction: () => {
          window.open(
            process.env.BASE_URL + 'xiumi/xiumi-ue-dialog-v5.html',
            'xiumiEditor',
            'height=' + (window.screen.availHeight - 100) + ',width=' + (window.screen.availWidth - 100) + ',top=50,left=50,help=no,resizable=no,status=no,scroll=no'
          )
        }
      })

      editor.ui.registry.addMenuItem('myPaste', {
        text: '粘贴',
        icon: 'paste-text', // 指定菜单项的图标
        shortcut: 'Ctrl+V', // 指定快捷键
        onAction: function () {
          console.log(tinymce.activeEditor, 78787878)
          // 在这里编写自定义菜单项的处理逻辑
          if (pluginConfig.value.isUse) {
            /*
             * app内容处理粘贴
             * 1.直接调用10086端口
             * 2.如果可以调用直接使用，不能调用则看唤醒协议是否支持
             * 3.try catch不支持唤醒协议则访问下载链接
             * */
            // const url = "http://127.0.0.1:10086/clip"
            pasteLoading.value = true
            const checkPromise = url => {
              return new Promise((resolve, reject) => {
                axios
                  .get(url)
                  .then(res => {
                    if (res.data.code) resolve(res)
                    else reject()
                  })
                  .catch(() => {
                    reject()
                  })
              })
            }
            const precheckClipPort = () => {
              const url = 'http://127.0.0.1:' + clip_port.value + '/clip'
              return checkPromise(url)
                .then(res => {
                  pasteLoading.value = false
                  if (res.data.code === 200) {
                    editor.insertContent(res.data.data)
                  } else {
                    ElMessage({
                      message: '无法粘贴该内容',
                      type: 'warning'
                    })
                  }
                  pasteLoading.value = false
                })
                .catch(() => {
                  if (clip_port.value < 10089) {
                    clip_port.value++
                    precheckClipPort()
                  } else {
                    ElMessageBox.confirm('无法粘贴该内容，是否启用粘贴插件工具', '启用确认', {
                      confirmButtonText: '启用',
                      cancelButtonText: '暂不启用'
                    })
                      .then(() => {
                        clip_port.value = store.state.content.clip_port
                        const foxClipLink = document.createElement('a')
                        foxClipLink.href = 'foxc://'
                        foxClipLink.target = '_self'
                        foxClipLink.click()
                        isPasting.value = false
                        nextTick(() => {
                          isPasting.value = true
                        })
                        // 判断用户界面失焦
                        let userOnblur = false
                        window.onblur = function () {
                          userOnblur = true
                        }
                        setTimeout(() => {
                          if (!userOnblur) {
                            ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">下载粘贴插件工具，下载文件包内含安装步骤</p></div>', '下载确认', {
                              distinguishCancelAndClose: true,
                              dangerouslyUseHTMLString: true,
                              confirmButtonText: '确认下载',
                              cancelButtonText: '暂不安装（本次发布不使用插件）'
                            })
                              .then(() => {
                                window.open(pluginConfig.value.downloadLink)
                              })
                              .catch(action => {
                                if (action === 'cancel') pluginConfig.value.isUse = false
                              })
                          }
                        }, 300)
                        pasteLoading.value = false
                      })
                      .catch(() => {
                        pluginConfig.value.isUse = false
                        pasteLoading.value = false
                      })
                  }
                })
            }
            precheckClipPort()
          } else {
            // 未开启插件时的粘贴处理
            navigator.clipboard
              .read()
              .then(async items => {
                if (pasteLoading.value) return
                pasteLoading.value = true

                try {
                  // 处理所有剪贴板项
                  for (const item of items) {
                    // 处理HTML内容(包含图片)
                    if (item.types.includes('text/html')) {
                      const htmlBlob = await item.getType('text/html')
                      const htmlContent = await htmlBlob.text()
                      editor.insertContent(htmlContent)
                    }
                    // 如果没有HTML内容，则尝试纯文本
                    else if (item.types.includes('text/plain')) {
                      const text = await item.getType('text/plain')
                      const textContent = await text.text()
                      editor.insertContent(textContent)
                    }
                  }

                  // 处理网络图片和本地图片
                  setTimeout(() => {
                    const wordImages = tinymce.activeEditor.dom.doc.querySelectorAll('img[src*="file://"]')
                    const urlImages = tinymce.activeEditor.dom.doc.querySelectorAll('img[src^="http"]')
                    let content = tinymce.activeEditor.getContent()
                    const baseUrl = store.state.base.groupSetting.baseUrl || ''
        
                    // 处理网络图片
                    const processImages = async () => {
                      for(let item of urlImages) {
                        if(!item.src.includes(baseUrl)) {
                          try {
                            const res = await uploadByUrl({url: item.src})
                            if (res.data) {
                              content = content.replace(item.src, res.data)
                            }
                          } catch (err) {
                            console.error('Failed to upload image:', err)
                          }
                        }
                      }
                      // 所有图片处理完成后，更新编辑器内容
                      editor.setContent(content)
                      editor.fire('change')
                    }
                    processImages()

                    // 处理本地图片
                    if (wordImages.length > 0) {
                      const hexStrings = parseRtf(evt.clipboardData.getData('text/rtf'))
                      const base64Images = hexStrings.map(hexObj => {
                        return convertHexToBase64(hexObj.hex)
                      })

                      wordImages.forEach((item, index) => {
                        item.src = `data:${hexStrings[index].type};base64,${base64Images[index]}`
                        tinymce.activeEditor.uploadImages()
                      })
                    }
                  }, 200)
                } catch (err) {
                  console.error('Failed to process clipboard content:', err)
                  ElMessage({
                    message: '无法粘贴该内容',
                    type: 'warning'
                  })
                } finally {
                  pasteLoading.value = false
                }
              })
              .catch(err => {
                console.error('Failed to read clipboard:', err)
                pasteLoading.value = false
                ElMessage({
                  message: '无法粘贴该内容',
                  type: 'warning'
                })
              })
          }
        }
      })
    }
  }
}
